# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(randomForest)
library(Boruta)
library(magrittr)
library(e1071)
library(optparse)
library(tidyverse)
library(readxl)
library(writexl)
library(DMwR)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "../train.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)
args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

sampleInfo <- read_csv(opt$g) %>%
  rename(ClassNote = Group) %>%
  select(c("SampleID", "ClassNote")) %>%
  mutate(ClassNote = as.character(ClassNote))

groups <- sampleInfo %>%
  .$ClassNote %>%
  unique()

parent <- paste0("./")
createWhenNoExist(parent)

data <- read_csv(str_c("data.csv")) %>%
  rename(Metabolite = SampleID) %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value")  %>%
  inner_join(sampleInfo, by = c("SampleID")) %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote))) %>%
  column_to_rownames("SampleID")

numColumns <- colnames(data) %>%
  keep(function(x) {
    startsWith(x, "Nubmer") || startsWith(x, "Number")
  })

data <- data %>%
  mutate_at(vars(numColumns), as.numeric) %>%
  mutate_at(vars(-numColumns), factor)

smoteData <- SMOTE(ClassNote ~ ., data,perc.over = 600,perc.under = 100)
table(smoteData$ClassNote)

trainOutTb<-smoteData %>%
  rownames_to_column("SampleID") %>%
  select(-"ClassNote")  %>%
  gather("Metabolite", "Value", -SampleID, factor_key = T) %>%
  spread(SampleID, "Value") %>%
  rename(SampleID=Metabolite)

write_csv(trainOutTb,"smote_data.csv")

smoteGroupTb<- smoteData %>%
  rownames_to_column("SampleID")  %>%
  select(c("SampleID","ClassNote")) %>%
  rename(Group=ClassNote)

write_csv(smoteGroupTb,"smote_group.csv")






